export const useTableStore = defineStore('table', () => {
  let tableHeaders = $ref([{
    table: 'testTable',
    dbStruct: [{}],
  }])

  let tableSettings = $ref([
    {
      id: 'testId',
      path: '',
      block: 'table',
      settings: [{}],
    },
  ])
  const fieldSetStruct = [
    { id: 'fieldName', text: '数据库字段名', type: 'string' },
    { id: 'alias', text: '别名', type: 'string' },
    { id: 'sNo', text: '顺序号', type: 'number' },
    { id: 'hide', text: '是否隐藏', type: 'boolean', value: false },
    { id: 'maskType', text: '掩码类型： 电话，身份证等', type: 'boolean', value: null },
    { id: 'width', text: '默认宽度', type: 'number', value: 150 },
    { id: 'align', text: '对齐方式', type: 'string', value: 'left' },
    { id: 'pinned', text: '固定方式', type: 'string', value: null },
    { id: 'fieldType', text: '数据库字段 type，搜索用', type: 'string', value: null },
    { id: 'showType', text: '字段类型', type: 'string', value: null },
    { id: 'filterType', text: '筛选控件类型', type: 'string', value: null },
    { id: 'filterDictType', text: '筛选字段映射类型', type: 'string', value: null },
    { id: 'filterOptions', text: '筛选自定义映射选项', type: 'object', value: null },
    { id: 'filterDict', text: '筛选字典映射分类ID', type: 'string', value: null },
    { id: 'filterFieldMap', text: '筛选联表映射设置', type: 'object', value: {} },
    { id: 'filterValue', text: '筛选默认值', type: 'string', value: null },
    { id: 'orderType', text: '默认排序方式', type: 'string', value: '' },
    { id: 'readonly', text: '是否只读', type: 'boolean', value: true },
    { id: 'isFuzzy', text: '是否加入模糊搜索', type: 'boolean', value: false },
    // 权限
    // { id: 'auth_show', text: '查看', type: 'boolean', value: true },
    // { id: 'auth_del', text: '删除', type: 'boolean', value: true },
    // { id: 'auth_edit', text: '编辑', type: 'boolean', value: true },
    // { id: 'auth_add', text: '新增', type: 'boolean', value: true },
    // { id: 'auth_import', text: '导入', type: 'boolean', value: true },
    // { id: 'auth_export', text: '导出', type: 'boolean', value: true },
    // 表单编辑属性
    { id: 'x-edit', text: '可否编辑', type: 'boolean', value: true },
    { id: 'x-component', text: '编辑控件', type: 'string', value: null },
    { id: 'x-component-props', text: '控件参数', type: 'object', value: null },
    { id: 'x-required', text: '必填', type: 'boolean', value: false },
  ]
  const getTableDef = (payload) => {
    const tableDef = clone(payload)
    return tableDef.map((e, idx) => {
      e.sNo = idx + 1
      const { description } = e
      if (isNilOrEmpty(e.alias) && isNotNilOrEmpty(description)) {
        if (!description.includes('主键') && !description.includes('Primary Key')) {
          const des = description.split(' ')
          if (des.length > 1) {
            e.alias = des[0]
          } else {
            e.alias = description
          }
        }
      }
      const defItem = Object.keys(e)
      fieldSetStruct.filter(v => !defItem.includes(v.id))
        .forEach(v => { e[v.id] = v.value })
      return e
    })
  }
  const getTableHeader = computed(() => (table) => {
    const header = tableHeaders.find(e => e.table === table)
    if (isNotNilOrEmpty(header)) {
      return header
    }
    return null
  })
  // 根据路径和方法，获取接口配置
  const getApiDefine = async (path, method) => {
    const resp = await getApiConfig(path, method)
    if (isNilOrEmpty(resp)) {
      return []
    }
    return mergeColDef(resp.define)
  }
  const getApiConfig = async (path, method) => {
    const { data, status } = await Fetch('/api/s/t/dict_api', { headers: { timestamp: Date.now() }, data: { api_method: method.toUpperCase(), api_path: path } })
    if (status !== 200 || data.code !== 0) {
      return null
    }
    return data.result.dataList[0]
  }
  // 获取表结构
  const getTableStruct = async (tableName) => {
    if (isNilOrEmpty(tableName)) { return [] }
    await aGetDbStruct(tableName)
    const header = tableHeaders.find(e => e.table === tableName)
    if (isNilOrEmpty(header)) {
      return []
    }
    return header.dbStruct
  }
  const mUpSertTableHeader = ({ table, dbStruct }) => {
    const idx = tableHeaders.findIndex(e => e.table === table)
    if (idx > -1) {
      tableHeaders.splice(idx, 1, dbStruct)
    } else {
      tableHeaders.push({ table, dbStruct })
    }
  }
  const mDeleteTableHeader = (table) => {
    const idx = tableHeaders.findIndex(e => e.table === table)
    if (idx > -1) {
      tableHeaders.splice(idx, 1)
    }
  }
  const mUpSertTableSettings = (payload) => {
    payload.forEach(p => {
      const idx = tableSettings.findIndex(e => e.id === p.id)
      if (idx > -1) {
        tableSettings.splice(idx, 1, p)
      } else {
        tableSettings.push(p)
      }
    })
  }
  const mDeleteTableSettings = (id) => {
    const idx = tableSettings.findIndex(e => e.id === id)
    if (idx > -1) {
      tableSettings.splice(idx, 1)
    }
  }
  const aGetDbStruct = async (tableName, update = false) => {
    if (!update) { // 表结构保存在 store，初始化的时候先从 store 里取，store里没有再从后台取。
      const hIdx = tableHeaders.findIndex(e => e.table === tableName)
      if (hIdx > -1 && isNotNilOrEmpty(tableHeaders[hIdx].dbStruct)) {
        return { code: 0, dbStruct: tableHeaders[hIdx].dbStruct, msg: '已存在' }
      }
    }
    const { status, data } = await Fetch(`/api/db/getTableInfo/${tableName}`)
    if (status === 200 && data.code === 0 && isNotNilOrEmpty(data.result)) {
      const dbStruct = data.result.columns.map((e, idx) => {
        return {
          fieldName: e.name,
          description: e.comment,
          fieldType: e.data_type,
          sNo: idx + 1,
        }
      })
      mUpSertTableHeader({ table: tableName, dbStruct })
      return { code: data?.code, dbStruct, msg: data?.msg }
    } else {
      return { code: data?.code, msg: data?.msg }
    }
  }
  // 通用搜索接口 TODO: 缓存数据
  const aTableSearch = async (tableName, params) => {
    const { status, data } = await Fetch(`/api/s/t/${tableName}`, { method: 'POST', data: { ...params, '@operator': 'or' } })
    if (status !== 200 || data.code !== 0) {
      console.log(data.msg)
      return []
    }
    return data.result.dataList
  }
  return {
    fieldSetStruct,
    getTableDef,
    tableHeaders: $$(tableHeaders),
    tableSettings: $$(tableSettings),
    getTableHeader,
    getApiDefine,
    getApiConfig,
    getTableStruct,
    mUpSertTableHeader,
    mUpSertTableSettings,
    mDeleteTableHeader,
    mDeleteTableSettings,
    aGetDbStruct,
    aTableSearch,
  }
}, { unistorage: { key: 'dict-api-config' } })

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useTableStore, import.meta.hot))
